
#include "hw_config.h"
#include "led.h"
#include "key.h"
#include "uart.h"

static volatile u16 s_key = 0;
static volatile u8 s_exit = 0;

void gpio_polling_key(void)
{
	s_exit = 0;

	while(!s_exit)
	{

		if( !inp(PINH, PH0) && !(s_key & KEY_KEY1) )
		{
			usart0_puts("Key1 Pressed.\r\n");
			s_key |= KEY_KEY1;
		}
		else if( inp(PINH, PH0) && (s_key & KEY_KEY1) )
		{
			usart0_puts("Key1 Released.\r\n");
			s_key &= ~KEY_KEY1;
		}

		if( !inp(PINH, PH1) && !(s_key & KEY_KEY2) )
		{
			usart0_puts("Key2 Pressed.\r\n");
			s_key |= KEY_KEY2;
		}
		else if( inp(PINH, PH1) && (s_key & KEY_KEY2) )
		{
			usart0_puts("Key2 Released.\r\n");
			s_key &= ~KEY_KEY2;
		}

		if( !inp(PINH, PH2) && !(s_key & KEY_KEY3) )
		{
			usart0_puts("Key3 Pressed.\r\n");
			s_key |= KEY_KEY3;
		}
		else if( inp(PINH, PH2) && (s_key & KEY_KEY3) )
		{
			usart0_puts("Key3 Released.\r\n");
			s_key &= ~KEY_KEY3;
		}

		if( !inp(PINH, PH3) && !(s_key & KEY_KEY4) )
		{
			usart0_puts("Key4 Pressed.\r\n");
			s_key |= KEY_KEY4;
		}
		else if( inp(PINH, PH3) && (s_key & KEY_KEY4) )
		{
			usart0_puts("Key4 Released.\r\n");
			s_key &= ~KEY_KEY4;
		}



		_delay_ms(20);
	}

}

void main(void)
{
	
	CLI();	// all interrupt disable

	bsp_usart0_gpio_init();
	bsp_usart0_init(F_CPU, EBaud115200, EData8, EParNone, EStop1, FALSE );	
	bsp_usart0_interrupt_enable();

	// set input
	cbi(DDRH, PH0);
	cbi(DDRH, PH1);
	cbi(DDRH, PH2);
	cbi(DDRH, PH3);

	// set output
	sbi(DDRH, PH4);
	sbi(DDRH, PH5);
	sbi(DDRH, PH6);
	sbi(DDRH, PH7);


	// led matrix on
	sbi(PORTH, PH4);
	sbi(PORTH, PH5);
	sbi(PORTH, PH6);
	sbi(PORTH, PH7);
	
	_delay_ms(1000);
	
	// led matrix off
	cbi(PORTH, PH4);
	cbi(PORTH, PH5);
	cbi(PORTH, PH6);
	cbi(PORTH, PH7);


	gpio_polling_key();

	SEI();	// all interrupt enable



	while(1)
	{

	}

}
